package com.fingard.dsp.bank;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;

import com.fingard.text.StringHelper;


public class DealTransSeq {

    private static Hashtable totalSeqHt = new Hashtable();
    public static Integer maxStep = 10;

    public static boolean addTransSeq(String p_transSeqID, String p_transTime) {
        if (StringHelper.isNullOrEmpty(p_transTime)) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            p_transTime = format.format(date);
        }
        Long transTime = Long.parseLong(p_transTime.replace(" ", "").replace("-", "").replace(":", "").substring(0, 12));
        try {
            if (totalSeqHt.containsKey(transTime)) {

                Enumeration<Long> e = totalSeqHt.keys();
                while (e.hasMoreElements()) {
                    long key = e.nextElement();
                    Hashtable currSeqHt = (Hashtable) totalSeqHt.get(key);
                    if (currSeqHt.containsKey(p_transSeqID)) {
                        return false;
                    }
                }
                Hashtable currSeqHt = (Hashtable) totalSeqHt.get(transTime);
                if (!currSeqHt.containsKey(p_transSeqID)) {
                    currSeqHt.put(p_transSeqID, 1);
                }
                return true;
            } else {
                Hashtable currSeqHt = new Hashtable();
                currSeqHt.put(p_transSeqID, 1);
                totalSeqHt.put(transTime, currSeqHt);
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            abandoned();
        }
    }

    public static void abandoned() {
        Hashtable tmpHt = (Hashtable) totalSeqHt.clone();
        Enumeration<Long> e = totalSeqHt.keys();
        while (e.hasMoreElements()) {
            long key = e.nextElement();
            DateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
            Date date = new Date();
            String currDate = format.format(date);
            long time = Long.parseLong(currDate);
            if (Math.abs(time - key) > maxStep) {
                tmpHt.remove(key);
            }
        }
        totalSeqHt = tmpHt;
    }
}
